package cn.fengsweb.tokyotyrant
{
	import cn.fengsweb.tokyotyrant.define.TokyoTyrantQueryFunctionName;
	
	import flash.utils.ByteArray;
	
	internal class PutMoreNoKeyHandler extends AbstractHandler
	{
		private var _putMoreNoKey:PutMoreNoKey;
		private var _uid:String;
		
		private var _keyArray:Array;
		private var _currentKey:String;
		private var _currentSendBytes:ByteArray;
		
		public function PutMoreNoKeyHandler(host:String, port:uint)
		{
			super(host, port);
		}
		
		public function connect(putMoreNoKey:PutMoreNoKey, ttr:TokyoTyrantResponder) : void
		{
			_ttc			= new TokyoTyrantConnection(_host, _port, false);
			_ttr			= ttr;
			_putMoreNoKey	= putMoreNoKey;
			_keyArray		= new Array;
			
			iteratePutOneNoKey();
		}
		
		private function iteratePutOneNoKey():void
		{
			if(0 < _putMoreNoKey.length){
				var query:TokyoTyrantQuery	= new TokyoTyrantQuery(TokyoTyrantQueryFunctionName.GENUID);
				defaultHandler(query.sendBytes, genuidHandler);
			}else{
				_ttr.result(_keyArray);
				_ttc.close();
			}
		}
		
		private function genuidHandler(recvBytes:ByteArray):void
		{
			var rnum:uint	= recvBytes.readUnsignedInt();
			var rsiz:uint	= recvBytes.readUnsignedInt();
			
			_currentKey		= recvBytes.readUTFBytes(rsiz);
			
			defaultHandler(_putMoreNoKey.getSendBytes(_currentKey), successhandler, failedHandler);
		}
		
		private function successhandler(recvBytes:ByteArray):void
		{
			_keyArray.push(_currentKey);
			
			iteratePutOneNoKey();
		}
		
		private function failedHandler():void
		{
			_keyArray.push(null);
			
			iteratePutOneNoKey();
		}
	}
}